/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cydonia.config;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.cydonia.misc.StrUtil;

/**
 *
 * @author franklin
 */
public class Configuration {

    public Map<String, String> parameters = new HashMap<String, String>();

    public static String USERNAME = "username";

    public static String PASSWORD = "password";

    public static String ENGINE = "engine";

    public static String DOMAIN = "domain";

    public static String UPDATETIME = "updatetime";

    public Configuration() {
        try {
            this.loadConfiguration();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Error. No valid configuration on /etc/cydonia/cydonia.conf");
            System.out.println("Run with --sample to copy configuration example.");
            System.exit(1);
        }
    }

    private void loadConfiguration() throws Exception {
        List<String> params = retornaLinhas("/etc/cydonia/cydonia.conf");
        for (Iterator<String> it = params.iterator(); it.hasNext();) {
            String linha = it.next();
            if (!StrUtil.nvl(linha.trim()).equals("")) {
                String[] pr = linha.trim().split("=");
                String key = pr[0].trim();
                String value = pr[1].trim();
                if (key.equalsIgnoreCase(USERNAME) || key.equalsIgnoreCase(PASSWORD) || key.equalsIgnoreCase(ENGINE) || key.equalsIgnoreCase(DOMAIN) || key.equalsIgnoreCase(UPDATETIME)) {
                    parameters.put(key, value);
                }
            }
        }
    }

    public String getValue(String key) {
        return this.parameters.get(key);
    }

    public List<String> retornaLinhas(String fileName) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        String line;
        List<String> rtn = new ArrayList<String>();
        while ((line = in.readLine()) != null) {
            if (!line.startsWith("#")) {
                if(line.contains("#")){
                    line = line.substring(0, line.indexOf("#"));
                }
                rtn.add(line);
            }
        }
        in.close();
        return rtn;
    }
}
